package shop.ynubeggar.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import shop.ynubeggar.exception.CustomException;
import shop.ynubeggar.service.VerifyService;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyServiceImpl implements VerifyService {

    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private Producer captchaProducer;

//    TODO 邮箱验证码和短信验证码的改造
    @Override
    public BufferedImage createVerification(String captchaKey){
        String captchaText = captchaProducer.createText();
        stringRedisTemplate.opsForValue().set(captchaKey, captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.SECONDS);
        return captchaProducer.createImage(captchaText);
    }

    public void verifyCode(String key, String value){
        String captchaText = stringRedisTemplate.opsForValue().get(key);
        if (captchaText != null && value != null && ObjectUtil.equals(captchaText, value)) {
            stringRedisTemplate.delete(key);
        } else {
            throw new CustomException(HttpStatus.NOT_FOUND,"captcha value does not match");
        }
    }
}
